package com.app.service.impl;

import com.app.controller.BlogController;
import com.app.entity.Blog;
import com.app.mapper.BlogMapper;
import com.app.service.BlogService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;

@Service
public class BlogServiceImpl implements BlogService {
    private static Logger log = Logger.getLogger(BlogService.class);
    @Autowired
    private BlogMapper blogMapper;

    @Override
    public ArrayList<Blog> getAllBlog() {
        return blogMapper.getAllBlog();
    }

    @Override
    public String addBlog(String params) {
        try {
            System.out.println("AddBlog() Params:"+params);
            //{"title":"1","content":"2","categories":["Vue.js"],"author":"王五"}
            JSONObject object = JSONObject.fromObject(params);
            Blog blog = (Blog) JSONObject.toBean(object, Blog.class);
            String categories = object.getString("categories");
            System.out.println(String.format("Blog title:%s,content:%s,categories:%s,author:%s",blog.getTitle(),blog.getContent(),categories,blog.getAuthor()));
            boolean bool = blogMapper.addBlog(blog.getTitle(), blog.getContent(), categories, blog.getAuthor());
            return bool ? "OK" : "Error";
        }catch (Exception e){
           log.error("addBlog Exception",e);
            return "Error";
        }
    }

    @Override
    public Blog getBlog(String id) {
        return blogMapper.getBlog(id);
    }
}
